<script setup lang='ts'>
import AMapLoader from '@amap/amap-jsapi-loader'
import { useMapBuildingList, useMapStatistics } from '@fl/api/add-elevator-api'
import type { MapBuildingListParams, MapStatisticsParams } from '@fl/api/add-elevator-api/model/map-model'
import { cloneDeep } from 'lodash-es'
import mapBuildingList from './components/map-building-list.vue'
import mapListSearch from './components/map-list-search.vue'

// defineOptions({
//     // eslint-disable-next-line vue/component-definition-name-casing
//     name: 'retrofit-elevator-map-list',
// })

const initialSearchState = {
    areaCode: '',
    areaName: '',
    streetCode: '',
    streetName: '',
    communityId: '',
    communityName: '',
    projectId: '',
    projectName: '',
    level: '1', // 统计级别,1:区;2.街道;3.社区;4.小区
}
const searchState = ref<MapStatisticsParams>(cloneDeep(initialSearchState))

const initialBuildingState = {
    pageIndex: 1,
    pageSize: 50,
    buildingName: '',
    projectId: '',
    type: '',
}
const buildingState = ref<MapBuildingListParams>(cloneDeep(initialBuildingState))

const mapList = ref<any>([])
const center = ref<Array<number>>([114.275385, 30.617457])
const zoom = ref<number>(10)
const marker = ref<any>()
const areaString = ref<string>() // 当前仅选择区时的区名，用来展示区边界
const dotDetail = ref<any>()
const showDotDetail = ref<boolean>(false) // 展示左上角点位详情
const showBuildingList = ref<boolean>(false) // 展示右侧楼栋列表
const areaList = ref<any>([])
const streetList = ref<any>([])
const communityList = ref<any>([])
const projectList = ref<any>([])
const greenIcon = 'https://public-obs-cdn.anjulian.com.cn/2025-01-15/83986ca9-788a-4e3c-8ef6-916e645cc735.png'
const blueIcon = 'https://public-obs-cdn.anjulian.com.cn/2025-01-15/dbc26a6b-8f67-4835-9e48-72d0019faa8b.png'
const redIcon = 'https://public-obs-cdn.anjulian.com.cn/2025-03-14/83265ed4-89fc-4f3f-bb34-8a92e7b38727.png'
const yellowIcon = 'https://public-obs-cdn.anjulian.com.cn/2025-03-14/ceaf3ca8-afa5-47ce-bde6-2aa2d734f96c.png'

// 1已加装-绿色、2已上报-黄色、3加装中-蓝色、4全部-红色
const iconDict = {
    1: greenIcon,
    2: yellowIcon,
    3: blueIcon,
    4: redIcon,
}

const backgroundDict = {
    1: 'backgroundGreen',
    2: 'backgroundYellow',
    3: 'backgroundBlue',
    4: 'backgroundRed',
}

const { data: statisticsData } = useMapStatistics(searchState)
const { data: buildingList, refetch: buildingRefetch } = useMapBuildingList(buildingState)

watchEffect(() => {
    if (statisticsData.value) {
        if (searchState.value.level === '1') {
            areaList.value = cloneDeep(statisticsData.value)
            mapList.value = areaList.value
        }
        else if (searchState.value.level === '2') {
            streetList.value = cloneDeep(statisticsData.value)
            mapList.value = streetList.value
        }
        else if (searchState.value.level === '3') {
            communityList.value = cloneDeep(statisticsData.value)
            mapList.value = communityList.value
        }
        else if (searchState.value.level === '4') {
            projectList.value = cloneDeep(statisticsData.value)
            mapList.value = projectList.value
        }
        initMap()
    }
    if (buildingList.value && searchState.value.level === '5') {
        mapList.value = cloneDeep(buildingList.value.records).reduce((pre, cur) => {
            cur.name = cur.building
            pre.push(cur)
            return pre
        }, [])
        clearBuildingInfo() // 刷新楼栋列表，也关闭左侧详情弹框
        if (mapList.value.length > 0) {
            initMap()
        }
    }
})

let map: any = null // 初始化地图
function initMap() {
    console.log('initMap')
    window._AMapSecurityConfig = {
        securityJsCode: '3d2b0d182274c8f36d175015792a5525', // 安全密钥
    }
    AMapLoader.load({
        key: '8e125d7a61c3c334ca9538a5c6798582',
        version: '2.0',
        plugins: [''],
    }).then((AMap) => {
        // 区、市边界
        if (!searchState.value.streetCode && !searchState.value.communityId && !searchState.value.projectId) {
            // 市边界：未选择任意区时展示
            if (!areaString.value) {
                AMap.plugin('AMap.DistrictSearch', () => {
                    const district = new AMap.DistrictSearch({
                        extensions: 'all',
                        level: 'city',
                    })
                    district.search('武汉市', (status, result) => {
                        const bounds = result.districtList?.[0]?.boundaries // 获取边界
                        if (bounds) {
                            for (let i = 0; i < bounds.length; i++) {
                                // 生成行政区划 polygon
                                const polygon = new AMap.Polygon({
                                    map, // 显示该覆盖物的地图对象
                                    strokeWeight: 2, // 轮廓线宽度
                                    path: bounds[i], // 多边形轮廓线的节点坐标数组
                                    fillOpacity: 0.1, // 多边形填充透明度
                                    fillColor: '#FFA8AA', // 多边形填充颜色
                                    strokeColor: '#ee0000', // 线条颜色
                                })
                            }
                            map.setFitView() // 将覆盖物调整到合适视野
                        }
                    })
                })
            }
            else {
                // 区边界：仅选择区时展示
                AMap.plugin('AMap.DistrictSearch', () => {
                    const district = new AMap.DistrictSearch({
                        extensions: 'all',
                        level: 'district',
                    })
                    district.search(areaString.value, (status, result) => {
                        const bounds = result.districtList[0].boundaries
                        if (bounds) {
                            for (let i = 0; i < bounds.length; i++) {
                                const polygon = new AMap.Polygon({
                                    map,
                                    strokeWeight: 2,
                                    path: bounds[i],
                                    fillOpacity: 0.7,
                                    fillColor: '#FFA8AA',
                                    strokeColor: '#ff0000',
                                })
                            }
                            map.setFitView()
                        }
                    })
                })
            }
        }

        // 临时处理点位数据
        if (searchState.value.level === '1') {
            // mapList.value = areaList.value
        }
        else if (searchState.value.level === '5') {
            zoom.value = 18
        }
        else if (searchState.value.level === '4') {
            zoom.value = 16
        }
        else if (searchState.value.level === '3') {
            zoom.value = 14
        }
        else if (searchState.value.level === '2') {
            zoom.value = 12
        }
        center.value = [Number(mapList.value?.[0]?.longitude), Number(mapList.value?.[0]?.latitude)]

        // 点位
        // 区、街道、社区：展示红色背景的content、无icon
        // 小区：无content，详情放到左上角、有icon
        map = new AMap.Map('mapBox', { // 设置地图容器id
            viewMode: '2D', // 是否为3D地图模式
            zoom: zoom.value,
            center: center.value, // 初始化地图中心点位置
            mapStyle: 'amap://styles/normal',
        })
        mapList.value.forEach((item) => {
            if (searchState.value.projectId) {
                // 1.楼栋样式
                // 处理icon（新）：1已加装-绿色、2已上报-黄色、3加装中-蓝色、4全部-红色
                const icon = new AMap.Icon({
                    size: new AMap.Size(40, 40),
                    image: iconDict[item.status],
                    imageSize: new AMap.Size(40, 40),
                })
                if (item.latitude != null && item.latitude !== '' && item.longitude != null) {
                    marker.value = new AMap.Marker({
                        position: new AMap.LngLat(item.longitude, item.latitude),
                        map,
                        icon,
                    })
                }
            }
            else {
                // 2.区、街道、社区、小区样式
                const icon = new AMap.Icon({
                    size: new AMap.Size(16, 8),
                    image: 'https://public-obs-cdn.anjulian.com.cn/2025-01-17/898576f1-cd0b-48ca-85ca-97af29441e60.png',
                    imageSize: new AMap.Size(16, 8),
                })
                if (item.latitude != null && item.latitude !== '' && item.longitude != null) {
                    marker.value = new AMap.Marker({
                        position: new AMap.LngLat(item.longitude, item.latitude),
                        map,
                        icon,
                    })
                }
                // 处理content
                const content = `<div style="border-radius:6px;background: #DA0004;padding: 8px 14px;color:#fff;text-align:center;line-height:24px;font-size:16px;cursor:pointer;box-shadow: 2px 0px 2px 0px rgba(0, 0, 0, 0.40);">`
                    + `<div style="font-weight:bold;">${item?.name || ''}</div>`
                    + `<div>共${item?.totalUnitNum || 0}楼栋/已上报${item?.submitNum || 0}部</div>`
                    + `<div>加装中${item?.processNum || 0}部/已加装${item?.num || 0}部</div>`
                    + '</div>'
                marker.value.setLabel({
                    direction: 'top',
                    offset: new AMap.Pixel(0, 4), // 设置文本标注偏移量
                    content, // 设置文本标注内容
                    icon,
                })
            }

            // 点位点击事件
            marker.value.on('click', () => {
                areaString.value = ''
                if (searchState.value.level === '5') {
                    // 等list数据出来
                    if (mapList.value.length === 0) {
                        // 小区有code，楼栋无code
                        if (item?.code) {
                            searchState.value.projectId = item.code
                            searchState.value.projectName = item.name
                            searchState.value.level = '4'
                            // 查楼栋数据用的单独的接口
                            showBuildingList.value = true
                            buildingState.value.projectId = item.code
                            buildingState.value.type = ''
                            buildingListRefetch()
                        }
                        return
                    }
                    dotDetail.value = item
                    showDotDetail.value = true
                }
                else if (searchState.value.level === '4') {
                    searchState.value.projectId = item.code
                    searchState.value.projectName = item.name
                    // 查楼栋数据用的单独的接口
                    showBuildingList.value = true
                    buildingState.value.projectId = item.code
                    buildingState.value.type = ''
                    buildingListRefetch()
                }
                else if (searchState.value.level === '3') {
                    searchState.value.communityId = item.code
                    searchState.value.communityName = item.name
                    searchState.value.level = '4'
                }
                else if (searchState.value.level === '2') {
                    searchState.value.streetCode = item.code
                    searchState.value.streetName = item.name
                    searchState.value.level = '3'
                }
                else if (searchState.value.level === '1') {
                    searchState.value.areaCode = item.code
                    searchState.value.areaName = item.name
                    searchState.value.level = '2'
                    areaString.value = item.name === '青山区' ? item.code : item.name
                }
            })
        })
        map.add(marker.value)
    }).catch((e) => {
        console.log(e)
    })
}

async function buildingListRefetch() {
    await buildingRefetch()
    searchState.value.level = '5'
}

function clearSearch() {
    console.log('清空')
    showDotDetail.value = false
    showBuildingList.value = false
    areaString.value = ''
}

// 顶部级联选择小区
function chooseProject(val) {
    buildingState.value.projectId = val
    buildingState.value.type = ''
    showBuildingList.value = true
}

// 清空楼栋列表
function clearBuilding() {
    buildingState.value.projectId = ''
    buildingState.value.type = ''
    showBuildingList.value = false
}

// 关闭左侧楼栋信息弹框
function clearBuildingInfo() {
    showDotDetail.value = false
}

// 传递区name，展示区边界
function toAreaStr(val) {
    areaString.value = val
}
</script>

<template>
    <div class="content">
        <div class="map">
            <div id="mapBox"
                 class="mapBox"
            />
        </div>
        <!-- 顶部搜索 -->
        <mapListSearch v-model:state="searchState"
                       v-model:area-list="areaList"
                       v-model:street-list="streetList"
                       v-model:community-list="communityList"
                       v-model:project-list="projectList"
                       @clear-search="clearSearch"
                       @choose-project="chooseProject"
                       @clear-building="clearBuilding"
                       @clear-building-info="clearBuildingInfo"
                       @to-area-str="toAreaStr"
        />
        <!-- 点位详情 -->
        <div v-if="showDotDetail"
             class="detail"
             :class="[backgroundDict[dotDetail.status]]"
        >
            <div class="line1">
                <div class="title">
                    {{ dotDetail.name }}
                </div>

                <!-- 1已加装-绿色、2已上报-黄色、3加装中-蓝色、4全部-红色 -->
                <el-tag v-if="dotDetail.status === '1'"
                        class="icon"
                        type="success"
                >
                    已加装
                </el-tag>

                <el-tag v-else-if="dotDetail.status === '2'"
                        class="icon"
                        type="warning"
                >
                    已上报
                </el-tag>

                <el-tag v-else-if="dotDetail.status === '3'"
                        class="icon"
                        type="danger"
                >
                    加装中
                </el-tag>

                <el-tag v-else-if="dotDetail.status === '4'"
                        class="icon"
                        type="primary"
                >
                    全部楼栋
                </el-tag>
            </div>

            <div class="line2">
                <span class="address">地址</span>

                <span class="address_content">{{ dotDetail.address }}</span>
            </div>

            <!-- <div class="line2">
                <span class="address">单元</span>

                <span class="address_content">{{ dotDetail.unit }}</span>
            </div> -->
        </div>
        <!-- 左下提示 -->
        <div v-if="showBuildingList"
             class="tips"
        >
            <!-- 1已加装-绿色、2已上报-黄色、3加装中-蓝色、4全部-红色 -->
            <div class="tip">
                <img class="img"
                     :src="redIcon"
                     alt=""
                >

                <span class="text">全部楼栋</span>
            </div>

            <div class="tip">
                <img class="img"
                     :src="yellowIcon"
                     alt=""
                >

                <span class="text">已上报</span>
            </div>

            <div class="tip">
                <img class="img"
                     :src="blueIcon"
                     alt=""
                >

                <span class="text">加装中</span>
            </div>

            <div class="tip">
                <img class="img"
                     :src="greenIcon"
                     alt=""
                >

                <span class="text">已加装</span>
            </div>
        </div>
        <!-- 楼栋列表 -->
        <mapBuildingList v-if="showBuildingList"
                         v-model:state="buildingState"
                         v-model:list="buildingList"
        />
    </div>
</template>

<style lang="scss" scoped>
.content {
    position: relative;
    width: 100%;

    .map {
        width: 100%;
        .mapBox {
            border: 1px solid #ddd;
            width: 100%;
            height: 80vh;
        }

        :deep(.amap-marker-label) {
            border: none;
            background: none;
        }
    }

    .detail {
        width: 360px;
        border-width: 0px 0px 4px 0px;
        box-shadow: 0px -4px 20px 0px rgba(0, 0, 0, 0.1);
        position: absolute;
        top: 100px;
        left: 24px;
        border-radius: 4px;
        padding: 16px;
        box-sizing: border-box;

        :deep(.el-tag.el-tag--danger) {
            --el-tag-text-color: #0052d9;
            border-color: rgba(217, 236, 255);
            background-color: rgba(236, 245, 255);
        }

        .line1 {
            position: relative;

            .title {
                color: #1d2129;
                font-size: 16px;
                font-weight: 600;
                width: 260px;
            }

            .icon {
                position: absolute;
                top: 0;
                right: 0;
            }
        }

        .line2 {
            display: flex;
            justify-content: space-between;
            margin-top: 10px;

            .address {
                width: 80px;
                color: #86909c;
            }

            .address_content {
                text-align: right;
            }
        }
    }

    .tips {
        width: 288px;
        height: 26px;
        background: #ffffff;
        border-radius: 2px;
        position: absolute;
        bottom: 40px;
        left: 24px;
        display: flex;
        justify-content: space-around;
        .tip {
            display: flex;
            align-items: center;
            .img {
                height: 16px;
                width: 16px;
            }
            .text {
                font-size: 12px;
                margin-left: 4px;
            }
        }
    }

    .backgroundBlue {
        background: linear-gradient(180deg, #ffffff 49%, #ebf2fc 100%);
        border-color: #0052d9;
    }

    .backgroundGreen {
        background: linear-gradient(180deg, #ffffff 49%, #e8ffef 100%);
        border-color: #00b042;
    }

    .backgroundRed {
        background: linear-gradient(180deg, #ffffff 49%, #ffd1cc 100%);
        border-color: #da0004;
    }

    .backgroundYellow {
        background: linear-gradient(180deg, #ffffff 49%, #ffe3c6 100%);
        border-color: #e9810b;
    }
}
</style>
